package tk.hoopy.zedtown.assets;

import java.io.File;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;;

public class XMLReader extends DefaultHandler {
	
	private SAXParser saxParser;
	protected String elementValue;
	private Asset newAsset;
	
	public Asset ParseDocument(File xmlDocument) {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			saxParser = factory.newSAXParser();
			saxParser.parse(xmlDocument, this);
		} catch (ParserConfigurationException | SAXException | IOException e) {
			e.printStackTrace();
			return null;
		}
		return newAsset;
	}
	
	@Override
    public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
		if(elementName.equalsIgnoreCase("tile")) {
			newAsset = new Tile();
		} else if(elementName.equalsIgnoreCase("entity")) {
			newAsset = new Entity();
		}
    }
	
    @Override
    public void endElement(String s, String s1, String element) throws SAXException {
        if(element.equalsIgnoreCase("title")) {
        	newAsset.SetName(elementValue);
        } else if(element.equalsIgnoreCase("texture")) {
        	newAsset.SetTexture(new ImageIcon(AssetManager.TEXTURES+"//"+elementValue).getImage());
        }
    }
    
    @Override
    public void characters(char[] ac, int i, int j) throws SAXException {
    	elementValue = new String(ac, i, j);
    }
	
}
